#include "Base.h"
#include "GamePlayer.h"
#include "MatchServer.h"
#include "MGProtocol.h"

CGamePlayer::CGamePlayer(void)
{
	m_nServerId = 0;
	memset(m_szGSPubIP, 0, sizeof(m_szGSPubIP));
	m_nPubPort = 0;
	m_dwGameId = 0;
	m_dwTotalUserCount = 0;
}

CGamePlayer::~CGamePlayer(void)
{
}

void CGamePlayer::OnDestroy()
{
    g_pMatchServer->DelGamePlayer(this);
}

Msg* CGamePlayer::CreateMsg(DWORD dwMsgId, int nLen)
{
	switch(dwMsgId)
	{
	case Msg_GM_GameSvrInfo:
		{
			return new GMGameSvrInfoMsg;
		}
	case Msg_GM_CreateMatch:
		{
			return new GMCreateMatchMsg;
		}
	case Msg_GM_GameResult:
		{
			return new GMGameResultMsg;
		}
	default:
		break;
	}
	return NULL;
}

BOOL CGamePlayer::OnMsg(Msg *pMsg)
{
	DWORD dwMsgId = pMsg->GetMsgId();
	switch(dwMsgId)
	{
	case Msg_GM_GameSvrInfo:
		{
			OnGameSvrInfo(pMsg);
		}
		break;
	case Msg_GM_CreateMatch:
		{
            OnCreateMatch(pMsg);
		}
		break;
	case Msg_GM_GameResult:
		{
			OnGameResult(pMsg);
		}
		break;
	default:
		break;
	}
    return TRUE;
}

BOOL CGamePlayer::OnGameSvrInfo(Msg *pMsg)
{
	GMGameSvrInfoMsg *pInfo = (GMGameSvrInfoMsg *)pMsg;
	strncpy((char*)m_szGSPubIP, (char*)pInfo->m_szGSPubIP, sizeof(m_szGSPubIP) - 1);
	m_nPort = pInfo->m_nPort;
	m_dwGameId = pInfo->m_dwGameId;

    g_pMatchServer->AddGamePlayer(this);
	return TRUE;
}

BOOL CGamePlayer::OnCreateMatch(Msg *pMsg)
{
    GMCreateMatchMsg *pAck = (GMCreateMatchMsg *)pMsg;

	CProduct *pProduct = g_pMatchServer->FindProduct(pAck->m_dwProductId);
	if(pProduct == NULL)
	{
		WriteLog("%s : %d CGamePlayer::OnCreateGame FindProduct return NULL, ProductId=%d", __FILE__, __LINE__, pAck->m_dwProductId);
		return TRUE;
	}
	CMatch *pMatch = pProduct->FindMatch(pAck->m_dwMatchId);
	if(pMatch == NULL)
	{
		WriteLog("%s : %d CGamePlayer::OnCreateGame FindMatch return NULL, MatchId=%d", __FILE__, __LINE__, pAck->m_dwMatchId);
		return TRUE;
	}

	if(!pMatch->PushMsg(pMsg, this))
	{
		WriteLog("PushMsg return FALSE");
	}
    return TRUE;
}

BOOL CGamePlayer::OnGameResult(Msg *pMsg)
{
    GMGameResultMsg *pResultMsg = (GMGameResultMsg *)pMsg;

	CProduct *pProduct = g_pMatchServer->FindProduct(pResultMsg->m_dwProductId);
	if(pProduct == NULL)
	{
		WriteLog("OnUserGameResult pProduct==NULL");
		return FALSE;
	}

	CMatch *pMatch = pProduct->FindMatch(pResultMsg->m_dwMatchId);
	if(pMatch == NULL)
	{
		WriteLog("OnUserGameResult pMatch==NULL");
		return FALSE; 
	}
 
	if(!pMatch->PushMsg(pMsg, this))
	{
		WriteLog("PushMsg return FALSE");
	}
	return TRUE;
}
